/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * 迭代实现
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function(root) {

    if(!root)return [];
    if(!root.left&&!root.right)return [root.val];

    let res = [],
        pre,
        p,
        stack = [root];

    while(stack.length>0){
        p = stack[stack.length-1];
        if((!p.left&&!p.right) || (pre&&(pre===p.left||pre===p.right))){
            res.push(p.val);
            pre = stack.pop();
        }else{
            if(p.right)stack.push(p.right);
            if(p.left)stack.push(p.left);
        }
    }

    return res;
};